//
//  LSPhotoView.swift
//  新浪微博---01次
//
//  Created by 李宗帅 on 16/5/9.
//  Copyright © 2016年 LS. All rights reserved.
//


import UIKit
import SnapKit
import SDWebImage
let LSPhotoViewMargin: CGFloat = 10
let LSPhotoItemMargin: CGFloat = 5
let LSPhotoItemWH = (UIScreen.mainScreen().bounds.width - 2 * LSPhotoViewMargin - 2 * LSPhotoItemMargin) / 3

let LSPhotoViewReuseIdentifier = "LSPhotoViewReuseIdentifier"

class LSPhotoView: UICollectionView ,UICollectionViewDataSource,UICollectionViewDelegate{
    
    var pic_urls: [LSPhotoViewModel]?{
        didSet {
            /// 得到图片的数量的世纪找到了.改变大小
            self.snp_updateConstraints { (make) -> Void in
                
                let size = calViewSize()
                
                //更新约束,要找到之前的约束视图以及约束
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
                
                //                make.size.equalTo(size)
            }
            
            //数据源从新加载之后  一定要记得刷新数据
            reloadData()
        }
    }
    
    var flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout:flowLayout)
        
        
        
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        
        dataSource = self
        
        delegate = self
        
        self.backgroundColor = UIColor.whiteColor()
        
        registerClass(LSPhotoViewCell.self, forCellWithReuseIdentifier: LSPhotoViewReuseIdentifier)
        
        //设置item大小  也就是cell  图片的大小
        
        flowLayout.itemSize = CGSizeMake(LSPhotoItemWH, LSPhotoItemWH)
        
        //cell之间的间距
        flowLayout.minimumLineSpacing = LSPhotoItemMargin
        
        flowLayout.minimumInteritemSpacing = LSPhotoItemMargin
        
        
    }
    
    //计算配图视图大小的方法
    private func calViewSize() -> CGSize {
        
        guard let count = pic_urls?.count else {
            return CGSizeZero
        }
        
        
        if count == 1 {
            
            //现在我们做的,是根据BUG驱动我们修改代码!!!!
            //图片太小  先改宽  随便给一个宽度
            //宽高比 ,失衡
            //获取图片地址
            let url = pic_urls?.first?.photo?.thumbnail_pic
            
            //获取图片
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url)
            
            flowLayout.itemSize = image.size
            
            //需要处理一下太窄的问题
            var size = image.size
            
            if size.width < 100 {
                //虽然支持中文,大家也不要多用中文
                let 系数 = 100/size.width
                
                size.height = 系数 * size.height
                
                size.width = 100
            }
            
            //需要处理太长的问题
            if size.height > 300 {
                
                size.height = 300
                
                let 系数 = 300/size.height
                
                size.width = 系数 * size.width
                
            }
            
            //返回图片的实际大小
            return image.size
            
        } else {
            flowLayout.itemSize = CGSizeMake(LSPhotoItemWH, LSPhotoItemWH)
        }
        
        if count == 4 {
            return CGSizeMake(2 * LSPhotoItemWH + LSPhotoItemMargin, 2 * (LSPhotoItemWH + LSPhotoItemMargin))
        }
        
        let row = (count - 1) / 3 + 1
        
        return CGSizeMake(UIScreen.mainScreen().bounds.width - 2 * LSPhotoViewMargin, (LSPhotoItemWH  + LSPhotoItemMargin) * CGFloat(row))
        
    }
    

//    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        
//        return 0
//    }
//    
//    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//        
//        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
//        
//        return cell
//    }
    
}

extension LSPhotoView {
    
     func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pic_urls?.count ?? 0
    }
    
     func  collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LSPhotoViewReuseIdentifier , forIndexPath: indexPath) as! LSPhotoViewCell
        
        cell.photo = pic_urls![indexPath.item]
        
        return cell
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let brower = SDPhotoBrowser()
        
        brower.sourceImagesContainerView = self
        
        brower.delegate = self
        
        brower.currentImageIndex = indexPath.item
        
        brower.imageCount = pic_urls!.count
        
        brower.show()
        
    }
    
}

//MARK:--SDPhotoBrowser的代理方法
extension LSPhotoView:SDPhotoBrowserDelegate {
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let urlStr = pic_urls![index].photo?.thumbnail_pic
        
        let url = urlStr?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: url!)
    }
    
    //返回原来的小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        //获取当前图片的角标
        let Index = NSIndexPath(forItem: index, inSection: 0)
        
        //获取当前的cell
        let cell = cellForItemAtIndexPath(Index) as? LSPhotoViewCell
        
        
        //返回当前cell的占位图片
        return cell?.iconImageView.image
    }
    
}

class LSPhotoViewCell: UICollectionViewCell {
    
    //接受数据源
    var photo: LSPhotoViewModel?{
        didSet {
            
             iconImageView.sd_setImageWithURL(photo?.thumbnail_pic)
            
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        addSubview(iconImageView)
        
        //让图片和cell一样大
        iconImageView.frame = bounds
        
    }
    
    //展示图片,懒加载imageView 
    private lazy var iconImageView:UIImageView = {
        
        let img = UIImageView()
        
        //记住几个图片的显示模式 不需要强记 用时再看就行
        
//        img.contentMode = .ScaleAspectFill
        
        return img
    }()
    
}

